package com.wang.code;

import java.util.Arrays;
public class _1ArrayListDemo {
	private Object[] value;
	private int size;
	public _1ArrayListDemo(int length) {
		super();
		value = new Object[length];
	}
	public _1ArrayListDemo() {
		this(10);
	}
	public _1ArrayListDemo(Object obj) {
		this(10);
		add(obj);
	}
	public void add(Object obj){
		growArrayCapcity();
		value[size] = obj;
		size++;
	}
	private void growArrayCapcity() {
		if (size == value.length) {
			value = Arrays.copyOf(value, value.length * 2);
		}
	}
	public int size(){
		return size;
	}
	@Override
	public String toString() {
		Object[] newArr = Arrays.copyOf(value,size);
		return Arrays.toString(newArr);
	}
	public Object searchByIndex(int index) throws IllegalAccessException{
		checkIndex(index);
		return value[index];
	}
	private void checkIndex(int index) throws IllegalAccessException {
		if (index > size-1 || index < 0) {
			throw new IllegalAccessException("请注意，下标范围：[0," + (size-1) + "]");//非法参数异常，给调用者提示
		}
	}
	public int searchByElement(Object ele){
		if (ele == null) {
			for (int i = 0; i < size; i++) {
				if (ele == value[i]) {
					return i;
				}
			}
		} else {
			for (int i = 0; i < size; i++) {
				if (ele.equals(value[i])) {
					return i;
				}
			}
		}
		return -1;
	}
	public void updateByIndex(int index,Object obj) throws IllegalAccessException{
		checkIndex(index);
		value[index] = obj;
	}
	public Object deleteByIndex(int index) throws IllegalAccessException{
		checkIndex(index);
		Object delete = value[index];
		System.arraycopy(value, index+1,value,index, size-index-1);//这里arraycopy方法是原生方法，是Java都用其他语言的方法，无法查看源码。但是这里已经处理的index+1 > 最后一个元素下标（size-1）的情况
		size--;
		return delete;
	}
	
	public void deleteByElement(Object ele) throws IllegalAccessException{
		int index = searchByElement(ele);
		if (index < 0) {
			return;
		}
		deleteByIndex(index);
	}
	
	public void insertByIndex(int index,Object obj) throws IllegalAccessException{
		if (index > size || index < 0) {
			throw new IllegalAccessException("请注意，插入的元素下标范围：[0," + size + "]");//非法参数异常，给调用者提示
		}
		if (index == size) {
			add(obj);
			return;
		}
		growArrayCapcity();
		System.arraycopy(value, index, value, index+1, size-index);
		value[index] = obj;
		size++;
	}
	public void clear(){
		value = new Object[10];
		size = 0;
	}
}
